package Thread;

import java.util.concurrent.TimeUnit;

public class ThreadDemo2 {

    public static void main(String[] args) {
        // 可以通过 synchronized 或者 Lock 来实现一个死锁代码
        // 所谓的死锁就是线程一拥有锁1，线程二拥有锁2，
        // 双方在拥有自身锁的同时尝试获取对方的锁，最终两个线程就会进入无线等待的状态，这就是死锁。

        Object lock1 = new Object();// 锁1
        Object lock2 = new Object();// 锁2

        Thread t1 = new Thread(() -> {
            //先获取锁1
            synchronized (lock1) {
                System.out.println(Thread.currentThread().getName() + "已获取到锁1");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //再尝试获取锁2
                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName() + "已获取到锁2");
                }
            }
        }, "t1");
        t1.start();//启动线程1

        Thread t2 = new Thread(() -> {
            //先获取锁2
            synchronized (lock2) {
                System.out.println(Thread.currentThread().getName() + "已获取到锁2");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //再尝试获取锁1
                synchronized (lock1) {
                    System.out.println(Thread.currentThread().getName() + "已获取到锁1");
                }
            }
        }, "t2");
        t2.start();//启动线程2
    }
}
